package vista;

import controlador.ControladorCompresor;
import controlador.ControladorDescompresor;
import controlador.ControladorFiltrosArchivos;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Gustavo Canul, Noe Cob, Arandi López
 */
public class VistaPrincipal extends javax.swing.JFrame {

    private ControladorCompresor controlCompresor;
    private ControladorDescompresor controlDescompesor;
    private String nombreArchivo;
    private static final String MENSAJE = "Seleccione una ruta para los archivos",
            MENSAJE_TXT = "Archivo de texto .txt",
            TEXTO_TXT = "txt",
            COMPRIMIDO_GAN = "gan",
            MENSAJE_COMPRIMIDO = "Archivo Comprimido .gan";

    /**
     *
     */
    public VistaPrincipal() {
        initComponents();
        txtDestino.setEditable(true);
        this.setResizable(false);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtOrigen = new javax.swing.JTextField();
        txtDestino = new javax.swing.JTextField();
        OpenOrigen = new javax.swing.JButton();
        OpenDestino = new javax.swing.JButton();
        About = new javax.swing.JButton();
        btnComprimir = new javax.swing.JButton();
        btnDescomprimir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Compresor de Archivos");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jLabel1.setText("Ruta origen:");

        jLabel2.setText("Ruta destino:");

        jLabel5.setText("Compresor de Archivos");

        txtOrigen.setEditable(false);
        txtOrigen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtOrigenActionPerformed(evt);
            }
        });

        txtDestino.setEditable(false);
        txtDestino.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtDestinoActionPerformed(evt);
            }
        });

        OpenOrigen.setText("...");
        OpenOrigen.setToolTipText("Archivos txt para comprimir, Archivos gan para descomprimir");
        OpenOrigen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OpenOrigenActionPerformed(evt);
            }
        });
        OpenOrigen.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                OpenOrigenKeyPressed(evt);
            }
        });

        OpenDestino.setText("...");
        OpenDestino.setToolTipText("Seleccione una ruta de salida para el archivo");
        OpenDestino.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OpenDestinoActionPerformed(evt);
            }
        });

        About.setText("About");
        About.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AboutActionPerformed(evt);
            }
        });

        btnComprimir.setText("Comprimir");
        btnComprimir.setToolTipText("Comprimir archivo txt");
        btnComprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnComprimirActionPerformed(evt);
            }
        });

        btnDescomprimir.setText("Descomprimir");
        btnDescomprimir.setToolTipText("Descomprimir archivo gan");
        btnDescomprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDescomprimirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnComprimir)
                                .addGap(18, 18, 18)
                                .addComponent(btnDescomprimir)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(About))
                            .addComponent(txtOrigen, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)
                            .addComponent(txtDestino, javax.swing.GroupLayout.Alignment.LEADING))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(OpenOrigen))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(OpenDestino)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtOrigen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(OpenOrigen))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDestino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(OpenDestino))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(About)
                    .addComponent(btnComprimir)
                    .addComponent(btnDescomprimir))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtOrigenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtOrigenActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtOrigenActionPerformed

    private void txtDestinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDestinoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtDestinoActionPerformed

    private void OpenOrigenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenOrigenActionPerformed
        // TODO add your handling code here:
        ControladorFiltrosArchivos controlFilter = new ControladorFiltrosArchivos(MENSAJE_TXT, TEXTO_TXT);
        ControladorFiltrosArchivos controlFiltro = new ControladorFiltrosArchivos(MENSAJE_COMPRIMIDO, COMPRIMIDO_GAN);

        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setMultiSelectionEnabled(false);
        //chooser.setCurrentDirectory(new File("./"));
        chooser.addChoosableFileFilter(controlFilter.getFiltroArchivos());
        chooser.addChoosableFileFilter(controlFiltro.getFiltroArchivos());
        chooser.setFileFilter(controlFilter.getFiltroArchivos());
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.showOpenDialog(this);

        String rutaOrigen = (chooser.getSelectedFile().getAbsolutePath());
        nombreArchivo = chooser.getSelectedFile().getName();
        System.out.println(rutaOrigen);
        txtOrigen.setText(rutaOrigen);

    }//GEN-LAST:event_OpenOrigenActionPerformed

    private void OpenDestinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenDestinoActionPerformed
        // TODO add your handling code here:
        //controlFilter = new ControladorFiltrosArchivos("Archivo de texto .txt", "txt");
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setMultiSelectionEnabled(false);
        //chooser.setCurrentDirectory(new File("./"));
        //chooser.setFileFilter(controlFilter.getFiltroArchivos());
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.showOpenDialog(this);

        String rutaDestino = (chooser.getSelectedFile().getPath() + comprobarSistemaOperativo());
        System.out.println(rutaDestino);
        txtDestino.setText(rutaDestino);
    }//GEN-LAST:event_OpenDestinoActionPerformed

    private void OpenOrigenKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_OpenOrigenKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_OpenOrigenKeyPressed

    private void AboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AboutActionPerformed
        // TODO add your handling code here:
        Licencia licencia = new Licencia(this, true);
        licencia.setVisible(true);
    }//GEN-LAST:event_AboutActionPerformed

    private void btnComprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnComprimirActionPerformed
        // TODO add your handling code here:

        if (txtDestino.getText().equals("") || txtOrigen.getText().equals("")) {
            JOptionPane.showMessageDialog(this, MENSAJE);

        } else {
            if (!obtenerExtensionArchivo(nombreArchivo).equals(".txt")) {
                JOptionPane.showMessageDialog(this, "Elija un archivo .txt para comprimir", "ERROR", JOptionPane.ERROR_MESSAGE);
            } else {
                try {
                    controlCompresor = new ControladorCompresor(nombreArchivo, txtOrigen.getText(), txtDestino.getText());
                } catch (IOException ex) {
                    Logger.getLogger(VistaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        txtDestino.setText("");
        txtOrigen.setText("");


    }//GEN-LAST:event_btnComprimirActionPerformed

    private void btnDescomprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDescomprimirActionPerformed
        // TODO add your handling code here:
        if (txtDestino.getText().equals("") || txtOrigen.getText().equals("")) {
            JOptionPane.showMessageDialog(this, MENSAJE);

        } else {
            if (!obtenerExtensionArchivo(nombreArchivo).equals(".gan")) {
                JOptionPane.showMessageDialog(this, "Elija un archivo .gan para descomprimir", "ERROR", JOptionPane.ERROR_MESSAGE);
            } else {
                controlDescompesor = new ControladorDescompresor(nombreArchivo, txtOrigen.getText(), txtDestino.getText());
            }
        }
        txtDestino.setText("");
        txtOrigen.setText("");
    }//GEN-LAST:event_btnDescomprimirActionPerformed

    /**
     *
     * @return
     */
    private String comprobarSistemaOperativo() {
        String nombreSO;
        nombreSO = System.getProperty("os.name");
        if (nombreSO.equals("Windows 7")) {
            return "\\";
        } else {
            return "/";
        }
    }

    private String obtenerExtensionArchivo(String ruta) {
        for (int i = ruta.length() - 1; i >= 0; i--) {
            if (ruta.charAt(i) == '.') {
                return ruta.substring(i);
            }
        }
        return null;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VistaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VistaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VistaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VistaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new VistaPrincipal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton About;
    private javax.swing.JButton OpenDestino;
    private javax.swing.JButton OpenOrigen;
    private javax.swing.JButton btnComprimir;
    private javax.swing.JButton btnDescomprimir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField txtDestino;
    private javax.swing.JTextField txtOrigen;
    // End of variables declaration//GEN-END:variables
}
